package com.kedsoft.andaily.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.io.ByteStreams;
import com.kedsoft.andaily.common.CommonResult;
import com.kedsoft.andaily.entity.TaskFile;
import com.kedsoft.andaily.service.TaskFileService;
import com.kedsoft.andaily.service.TaskService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by LGP on 2019/4/29.
 */

@RestController
@RequestMapping(value = "/api/taskfile")
public class TaskFileApiController {
    @Autowired
    TaskService taskService;

    @Autowired
    TaskFileService taskFileService;

    @ApiOperation(value = "获取任务图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "taskId", dataType = "int", required = true, value = "所属任务ID")
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResult<List<TaskFile>> getList(@RequestParam("taskId") int taskId)
    {
        Wrapper<TaskFile> wrapper = new EntityWrapper<>();
        wrapper.eq("taskid", taskId);
        return CommonResult.success(taskFileService.selectList(wrapper));
    }

    @ApiOperation(value = "任务图片添加")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "filename", dataType = "String",defaultValue = "-", required = false, value = "图片描述"),
            @ApiImplicitParam(paramType = "query", name = "filetype", dataType = "int",defaultValue = "1", required = true, value = "图片类型1：操作前2：操作后"),
            @ApiImplicitParam(paramType = "query", name = "taskid", dataType = "int", required = true, value = "所属任务ID")
    })
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public CommonResult<TaskFile> save(HttpServletRequest request, TaskFile param, @RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return CommonResult.fail("上传失败，请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        ServletContext application = request.getServletContext();
        String savePath = "C:\\picture\\";
        // 文件保存目录URL
        String saveUrl = request.getContextPath()+"/files/";
        System.out.println("saveUrl=============================="+saveUrl);
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 检查目录写权限
//        if (!uploadDir.canWrite()) {
//            return CommonResult.fail("上传目录没有写权限。");
//        }

        String dirName = getDirName(extMap,fileExt);
        // 创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 检查扩展名

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        param.setFileurl(saveUrl + newFileName);
        try {
            ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile));
            param.setCrtime(new Date());
            param.setTask("-");
            taskFileService.insert(param);
            EntityWrapper<TaskFile> wrapper = new EntityWrapper<>();
            wrapper.eq("taskid",param.getTaskid());
            wrapper.eq("fileurl",param.getFileurl());
            wrapper.orderBy("id",false);
            TaskFile result = taskFileService.selectOne(wrapper);
            return CommonResult.success(result);
        } catch (Exception e) {
            return CommonResult.fail("添加数据失败："+e.getMessage());
        }
    }

    @ApiOperation(value = "任务图片删除")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", dataType = "int", required = true, value = "图片ID")
    })
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public CommonResult deleteTaskFile(@RequestParam Integer id){
        taskFileService.deleteById(id);
        return CommonResult.success("删除数据成功");
    }

    private String getDirName(HashMap<String, String> map,String ext){
        for(String key:map.keySet()){
            String value = map.get(key);
            boolean status = value.contains(ext);
            if(status){
                return key;
            }
        }
        return "file";
    }
}
